///新版本
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_ahj_app/TestViewModel.dart';
import 'package:flutter_ahj_app/app/HttpRequest.dart';
import 'package:flutter_ahj_app/app/my/Beans/CheckDataVersionData.dart';
import 'package:flutter_ahj_app/app/my/view/subViews/UserInfo.dart';
import 'package:flutter_ahj_app/app/NewMine/MyViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/HttpUtils/HttpBaseConst.dart';
import 'package:flutter_ahj_app/base/cunchu/Constant.dart';
import 'package:flutter_ahj_app/base/cunchu/UserInfoUtils.dart';
import 'package:flutter_ahj_app/base/rouleutils/RouleUtils.dart';
import 'package:flutter_ahj_app/base/utils/ApkUpdataUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetFilesPath.dart';
import 'package:flutter_ahj_app/base/utils/ShowFiles/GetImageWidget.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/eventBus.dart';
import 'package:flutter_ahj_app/base/utils/font_utils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/utils/permission/PerUtils.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

import '../../../base/basewidget/view/BaseWidget.dart';

class AboutUsPageView extends BaseStatefulWidget {
  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    return AboutUsState();
  }
}

class AboutUsState extends BaseState<TestViewModel, AboutUsPageView> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Future.delayed(Duration.zero, () {
      _pckInfo();
    });
  }

  @override
  Widget initWidget() {
    // TODO: implement initWidget
    return new Scaffold(
      backgroundColor: SQColor.theme_Bg_color,
      appBar: new AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: SQColor.theme_color,
        title: JText(
          '关于我们',
          color: SQColor.white,
          fontSize: 18,
        ),
      ),
      body: _bodyView(),
    );
  }

  _bodyView() {
    return SingleChildScrollView(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          new Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(top: 46),
            child: _topView(),
          ),
          Container(
            child: _listContent(),
            margin: EdgeInsets.only(top: 36),
          )
        ],
      ),
    );
  }

  String versionName = "";
  _pckInfo() async {
    PackageInfo pckInfo = await PackageInfo.fromPlatform();
    setState(() {
      versionName = "当前版本V${pckInfo.version}";
    });
  }

  _topView() {

    return Column(
      children: [
        Image.asset(
          "img/logo_yuanjiao.png",
          width: Dimens.dimens80,
          height: Dimens.dimens80,
        ),
        SizedBox(
          height: Dimens.dimens12,
        ),
        JText(
          "青柠",
          fontSize: 12,
          color: SQColor.black_666666,
          fontWeight: FontWeight.w400,
        ),
        SizedBox(
          height: Dimens.dimens4,
        ),
        JText(
          versionName,
          fontSize: 12,
          color: SQColor.black_666666,
          fontWeight: FontWeight.w400,
        ),
      ],
    );
  }




  _listContent() {
    return Container(
      margin: EdgeInsets.only(left: Dimens.dimens14, right: Dimens.dimens14),
      decoration: BoxDecoration(
        color: SQColor.white,
        borderRadius: BorderRadius.all(Radius.circular(4.0)),
      ),
      child: Column(
        children: [
          _itemcontent("检查更新"),
          Container(
            height: 1.0,
            color: SQColor.lightGray1,
            margin:
                EdgeInsets.only(left: Dimens.dimens16, right: Dimens.dimens16),
          ),
          _itemcontent("用户隐私协议"),
        ],
      ),
    );
  }

  _itemcontent(String content) {
    return InkWell(
      onTap:() {
        if (content == '用户隐私协议') {
          Navigator.pushNamed(context, "/WebViewUntil",
                arguments: {"title": '用户协议', "url": 'https://ahj-static.oss-cn-beijing.aliyuncs.com/html/index.html'});
        }else if (content == '检查更新') {
          _checkPermission();
        }
      },
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Container(
                  height: 59,
                  padding: EdgeInsets.only(left: Dimens.dimens16),
                  child: Row(
                    children: [
                      JText(
                        content,
                        color: SQColor.black_333333,
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Container(
                padding: EdgeInsets.only(right: Dimens.dimens18),
                child: Center(
                  child: Icon(
                    Icons.arrow_forward_ios_outlined,
                    size: Dimens.dimens15,
                    color: SQColor.black_999999,
                  ),
                )),
          ],
        ),
        height: 59,
      ),
    );
  }

  CheckDataVersionData version;

  Future _checkPermission() async {
    if (HttpBaseConst.serverUrl.contains("api.platform.anhuanjia.com")) {
      String result =
      await PerUtils.checkPermission(context, [Permission.storage]);
      if (result == "1" && Platform.isAndroid) {
        _checkVersion();
      }
    }
    // else {
    //   _checkVersion();//测试环境
    // }
  }

  _checkVersion() async{
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var _DATA = {
      'version': packageInfo.version,
    };
    HttpRequest.checkVersion(_DATA).listen((request) {
      version = CheckDataVersionData.fromJson(request);
      if(version.code == "0") {
        if (version.data.updateState) {
          // 不是最新版本
          _askedToLead(context, version.data);
        } else {
          ToastUtils.showToast("已是最新版本");
        }
      }else {
        ToastUtils.showToast(version.msg);
      }
    }, onError: (e) {
      //请求异常等
      print(e);
    });
  }

  bool isDownloading = false;
  String apkPath = "";
  int count, total;
  // 提示框
  _askedToLead(BuildContext context, CheckVersion version) {
    StatefulBuilder sb = StatefulBuilder(
      builder: (context, mSetState) {
        return WillPopScope(
          child: new AlertDialog(
            title: new Text("版本更新"),
            content: _dialogBody(version.updateDescribe),
            actions: <Widget>[
              new FlatButton(
                  child: Text(isDownloading ? "取消" : "现在更新"),
                  onPressed: () {
                    mSetState(() {
                      if (!isDownloading) {
                        isDownloading = true;
                        if (version.downloadUrl == "") {
                          this.count = 0;
                          this.total = 0;
                          isDownloading = false;
                          ToastUtils.showToast("下载地址为空");
                        } else {
                          _download(
                              context, version.downloadUrl, mSetState);
                        }
                      } else {
                        this.count = 0;
                        this.total = 0;
                        isDownloading = false;
                        Navigator.of(context).pop();
                        if (version.forceUpdate == 1) {
                          // 强制更新退出登录
                          exit(0);
                        }
                      }
                    });
                  }),
              Offstage(
                offstage: isDownloading,
                child: new FlatButton(
                    child: new Text("稍后再说"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      if (version.forceUpdate == 1) {
                        // 强制更新退出登录
                        exit(0);
                      }
                    }),
              )
            ],
          ),
          onWillPop: () async {
            return Future.value(false);
          },
        );
      },
    );
    showDialog(
        context: context, barrierDismissible: false, builder: (context) => sb);
  }

  _dialogBody(String words) {
    if (isDownloading) {
      try {
        int progress = (count / total * 100).toInt();
        return Text("下载进度：$progress%");
      } catch (e) {
        return Text("下载进度：0%");
      }
    } else {
      List<String> list = List();
      list.addAll(words.split("<abc>"));

      return SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: _getItems(list),
        ),
      );
    }
  }


  List<Widget> _getItems(List<String> list) {
    // 不带分割线的item
    List<Widget> items = new List();
    for (int i = 0; i < list.length; i++) {
      items.add(Container(
        padding: EdgeInsets.only(top: Dimens.dimens4, bottom: Dimens.dimens4),
        child: Text(list[i]),
      ));
    }
    return items;
  }

  //开始下载附件
  void _download(
      BuildContext context, String downPath, StateSetter mSetState) async {
    String result =
    await PerUtils.checkPermission(context, [Permission.storage]);
    if (result == "1") {
      final dir = await getExternalStorageDirectory();
      apkPath = dir.path + '/ehs3.apk';
      print(apkPath);
      File file = new File(apkPath);
      if (await file.exists()) {
        await file.delete();
      }
      BaseOptions _options = new BaseOptions(
          connectTimeout: 50000,
          receiveTimeout: 100000,
          headers: {"cache-control": "no-chache"});

      Dio dio = new Dio(_options);
      Response response = await dio.download(downPath, apkPath,
          onReceiveProgress: (count, total) {
            mSetState(() {
              this.count = count;
              this.total = total;
              if (count == total) {
                // 下载完毕
                ApkUpdataUtils.install(apkPath);
                isDownloading = false;
                Navigator.of(context).pop();
              }
            });
          });
    } else {
      ToastUtils.showToast("请先开启权限再下载");
    }
  }


}
